package com.gqk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gqk.common.handler.GlobalExceptionHandler;
import com.gqk.common.result.Result;
import com.gqk.common.result.ResultCodeEnum;
import com.gqk.common.util.JwtHelper;
import com.gqk.common.util.MD5;
import com.gqk.exception.YiYunGlobalException;
import com.gqk.model.system.SysUser;
import com.gqk.service.SysUserService;
import com.gqk.vo.system.LoginVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 后台登录登出
 * </p>
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    SysUserService sysUserService;
    /**
     * 登录
     * @return
     */
    @PostMapping ("login")
    public Result login(LoginVo loginVo)  {
        // 1.获取用户输入的账号密码
        String username = loginVo.getUsername();
        String password = loginVo.getPassword(); // 用户输入的
        // 2.根据用户名查询一个用户
        // 2.1 设定条件
        LambdaQueryWrapper<SysUser> wrapper =
                new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username);
        // 2.2 调用service查询用户
        SysUser oneUser = sysUserService.getOne(wrapper);
        // 3.判断用户名是否存在
        if(oneUser == null){
            throw new YiYunGlobalException(4001,"用户名不存在");
        }
        // 4.获取查询出来的用户密码
        String passwordQuery = oneUser.getPassword(); // 数据库中保存的密码
        // 5.将用户输入的密码进行加密再判断
        String passwordInput = MD5.encrypt(password);
        if(!passwordInput.equals(passwordQuery)){
            throw new YiYunGlobalException(ResultCodeEnum.LOGIN_USERNAME_ERROR);
        }
        // 6.判断是否禁用
        if(oneUser.getStatus() == 0){
            throw new YiYunGlobalException(4001,"该账号被禁用");
        }
        // 7.生成token(令牌)
        String token = JwtHelper.createToken(oneUser.getId(), oneUser.getUsername());
        Map<String, String> map = new HashMap<>();
        map.put("token",token);
        return Result.ok(map);
    }
    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("info")
    public Result info(HttpServletRequest request) {
        String username = JwtHelper.getUsername(request.getHeader("token"));
        Map<String, Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }

    /**
     * 注销登录
     * @return
     */
    @GetMapping("/logout")
    public Result logout(){
        return Result.ok();
    }

}
